<template>
  <div class="app-container">
    <el-button v-if="$store.getters.buttons.includes('role/create')" size="mini" type="primary"
      @click="handleAddRole">新角色</el-button>

    <!-- <el-table stripe :data="rolesList" style="width: 100%;margin-top:30px;" @row-dblclick="handleEdit"> -->
    <el-table stripe :data="rolesList" style="width: 100%;margin-top:30px;">
      <el-table-column align="center" label="ID" width="145">
        <template slot-scope="scope">
          {{ scope.row.key }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="角色" width="145">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="描述">
        <template slot-scope="scope">
          {{ scope.row.description }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="150">
        <template v-if="scope.row.name !== 'admin'" slot-scope="scope">
          <el-button v-if="$store.getters.buttons.includes('role/update')" type="primary" circle size="mini"
            icon="el-icon-edit" @click="handleEdit(scope.row)" />
          <el-button v-if="$store.getters.buttons.includes('role/delete')" type="danger" circle size="mini"
            icon="el-icon-delete" @click="handleDelete(scope)" />
        </template>
      </el-table-column>
    </el-table>

    <pagination :total="pageTotal" :page.sync="query.currentPage" :limit.sync="query.take" @pagination="getRoles" />

    <el-dialog :visible.sync="dialogVisible" :title="dialogType === 'edit' ? '角色编辑' : '新增角色'">
      <el-form :model="role" label-width="80px" label-position="left">
        <el-form-item label="角色">
          <el-input v-model="role.name" placeholder="角色名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="role.description" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"
            placeholder="角色描述" />
        </el-form-item>
        <el-form-item label="相应权限">
          <el-tree ref="tree" highlight-current default-expand-all :check-strictly="checkStrictly" :data="routesData"
            :props="defaultProps" show-checkbox node-key="path" class="permission-tree" />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRole">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import permission from '@/directive/permission/index.js'
import path from 'path'
import { deepClone } from '@/utils'
import { getRoutes, getRoles, addRole, deleteRole, updateRole } from '@/api/role'
const defaultRole = {
  key: '',
  name: '',
  description: '',
  routes: []
}

export default {
  directives: { permission },
  components: { Pagination },
  data() {
    return {
      pageTotal: 5,
      query: {
        currentPage: 1,
        skip: 10,
        take: 10
      },
      role: Object.assign({}, defaultRole),
      routes: [],
      rolesList: [],
      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      }
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  created() {
    // 从服务器获取所有路由和角色列表
    this.getRoutes()
    this.getRoles()
  },
  methods: {
    async getRoutes() {
      const { data } = await getRoutes()
      this.routes = data
    },
    async getRoles() {

      const { take, currentPage } = this.query
      this.query.skip = take * (currentPage - 1)
      const { data } = await getRoles(this.query)
      this.rolesList = data[0]
      this.pageTotal = data[1]

    },

    // 重塑路由结构，使其看起来与侧边栏相同
    generateRoutes(routes, basePath = '/') {
      const res = []
      for (let route of routes) {
        // 跳过一些路由
        if (route.hidden) { continue }

        const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route)

        if (route.children && onlyOneShowingChild && !route.alwaysShow) {
          route = onlyOneShowingChild
        }

        const data = {
          path: route.path,
          // title: route.meta && route.meta.title
          title: route.title && route.title
        }

        // 递归子路由
        if (route.children) {
          data.children = this.generateRoutes(route.children, data.path)
        }
        res.push(data)
      }
      return res
    },
    generateArr(routes) {
      let data = []
      routes.forEach(route => {
        data.push(route)
        if (route.children) {
          const temp = this.generateArr(route.children)
          if (temp.length > 0) {
            data = [...data, ...temp]
          }
        }
      })
      return data
    },
    handleAddRole() {
      this.role = Object.assign({}, defaultRole)
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    getCheckState(res, routes) {
      for (const route of routes) {
        if (route.children) {
          this.getCheckState(res, route.children)
        }
        res.push(route.path)
      }
      return res
    },
    handleEdit(row) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.checkStrictly = true
      this.role = deepClone(row)
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys(this.getCheckState(new Array(), row.routes))// 设置节点勾选状态
        // 设置节点的已检查状态不会影响其父节点和子节点
        this.checkStrictly = false
      })
    },
    handleDelete({ $index, row }) {
      if (row.name === 'admin') {
        return this.$message({
          type: 'error',
          message: '这玩意儿不能删！'
        })
      }
      this.$confirm(`确定要删除角色 【${row.name}】 ？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data } = await deleteRole(row.key)
        if (!data.error) {
          this.rolesList.splice($index, 1)
        }
        this.$message({
          type: data.error ? 'error' : 'success',
          message: data.error ? `【${row.name}】 角色下有用户不能删除！` : `删除 【${row.name}】 角色成功！`
        })
      }).catch(err => { })
    },
    generateTree(routes, basePath = '/', checkedKeys) {
      const res = []
      for (const route of routes) {
        const routePath = route.path
        if (route.children) {
          route.children = this.generateTree(route.children, routePath, checkedKeys)
        }
        if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1)) {
          res.push(route)
        }
      }
      return res
    },
    async confirmRole() {
      const isEdit = this.dialogType === 'edit'
      const checkedKeys = this.$refs.tree.getCheckedKeys()
      this.role.routes = this.generateTree(deepClone(this.routes), '/', checkedKeys)
      if (isEdit) {
        const { data } = await updateRole(this.role.key, this.role)
        if (data.affected > 0) {
          this.getRoles()
        } else {
          return this.$message({
            type: 'error',
            message: '修改失败接口异常！'
          })
        }
      } else {
        const { data } = await addRole(this.role)
        this.role.key = data.id// 不需要 this.getRoles() 直接操作数据减少数据请求 提升性能
        this.rolesList.push(this.role)
      }

      const { description, key, name } = this.role
      this.dialogVisible = false
      this.$notify({
        title: 'SUCCESS',
        dangerouslyUseHTMLString: true,
        message: `
            <!--<div>Role Key: ${key}</div>-->
            <div>角色名称: ${name}</div>
            <div>描述: ${description}</div>
          `,
        type: 'success'
      })
    },
    // reference: src/view/layout/components/Sidebar/SidebarItem.vue
    onlyOneShowingChild(children = [], parent) {
      let onlyOneChild = null
      const showingChildren = children.filter(item => !item.hidden)

      // 当只有一个子路由时，默认情况下显示该子路由
      if (showingChildren.length === 1) {
        onlyOneChild = showingChildren[0]
        onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
        return onlyOneChild
      }

      // 如果没有要显示的子路由，则显示父路由
      if (showingChildren.length === 0) {
        onlyOneChild = { ...parent, path: '', noShowingChildren: true }
        return onlyOneChild
      }

      return false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }

  .block {
    margin-top: 1%;
  }

  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
